import React from 'react';
import { View, TouchableHighlight, StyleSheet, Dimensions } from 'react-native';
import Variables ,  { changeTheme ,useTheme} from '../../config/theme/styles/index';

export default class ThemeProvider extends React.Component {
  constructor(props) {
    super(props);
   
  }

  componentWillMount(){
    let { args , theme } = this.props

    // 执行主体色的切换
    if(theme){
      this.changeThemeFun(theme)
    }

    if(args){
       this.useThemeFun(args)
    }

  }

  
  componentWillReceiveProps(props,state){
    console.log(props,state,"componentWillReceiveProps");

    if(props.theme != this.props.theme){
        
        this.changeThemeFun(props.theme)
    }

   

    if(props.args){
       //遍历args 查看是否和先前的不一致
       if(this.props.args){
          let isUpdate = Object.keys(props.args).some((key)=>{
            return props.args[key]!=this.props.args[key]
          })
          isUpdate &&  this.useThemeFun(args)
       }
      
     
    }
  }

  //切换主题 换肤功能
  changeThemeFun=(theme)=>{
    
    console.log("changeThemeFeature start", theme);

    try {
        if( typeof theme =="string"){
            changeTheme(theme)
           
        }else {
            this.throwNewError("theme","string")
        }
    } catch (error) {
        console.log(error,"themeProvider error");
    }
  }

  // 调用args 换肤功能
  useThemeFun = (args)=>{

    console.log("useThemeFeature start", args);

    try {
        if( typeof args =="object"){
            useTheme(theme)
        
        }else {
            this.throwNewError("args","object")
        }
    } catch (error) {
        console.log(error,"themeProvider error");
    }
  }


  componentDidUpdate(){

  }

  componentDidCatch(error){
    console.log(error); 
  }

  // 参数报错
  throwNewError = ( params, type )=>{
    throw new Error(`themeProvider params error, ${params} is not ${type}`)
  }


  render() {
   
     return (
        <View>
            {this.props.children}
        </View>
     )
  }
}